package net.flyinggroup.websocket.client;

import lombok.SneakyThrows;
import org.springframework.web.reactive.socket.WebSocketMessage;
import org.springframework.web.reactive.socket.client.ReactorNettyWebSocketClient;
import org.springframework.web.reactive.socket.client.WebSocketClient;
import reactor.core.publisher.Flux;

import java.net.URI;
import java.time.Duration;

public class ReactiveJavaClientWebSocket {
    @SneakyThrows
    public static void main(String[] args) {
        WebSocketClient client = new ReactorNettyWebSocketClient();
        client.execute(URI.create("ws://localhost:8080/event-emitter"),
                session ->
                        session.send(
                                Flux.interval(Duration.ofMillis(1000L))
                                        .map(i -> session.textMessage("event from client" + i))
                        )
                                .thenMany(session.receive().map(WebSocketMessage::getPayloadAsText).log())
                                .then())
                .subscribe(System.out::println);
        Thread.sleep(10000L);
    }
}
